package com.example.sxmall.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.sxmall.common.lang.Const;
import com.example.sxmall.common.lang.Result;
import com.example.sxmall.dao.pojo.AdminsPermis;
import com.example.sxmall.dao.pojo.PermPerc;
import com.example.sxmall.dao.pojo.Permission;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.stylesheets.LinkStyle;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhang
 * @since 2022-03-22
 */
@RestController
@RequestMapping("/permission")
public class PermissionController extends BaseController {

    @PreAuthorize("hasAuthority('sys:perm:list')")
    @GetMapping("/info/{perid}")
    public Result info(@PathVariable("perid") Integer perid){

        Permission permission = permissionService.getById(perid);
        List<PermPerc> permPercs = permPercService.list(new QueryWrapper<PermPerc>().eq("perid",perid));

        //获取权限等级相关联的权限id
        List<Integer> pcids = permPercs.stream().map(permPerc -> permPerc.getPcid()).collect(Collectors.toList());

        permission.setPcid(pcids);

        return Result.succ(permission);
    }

    @PreAuthorize("hasAuthority('sys:perm:list')")
    @GetMapping("/list")
    public Result list(String name){
        /*分页*/
        Page<Permission> pageData = permissionService.page(getPage(),new QueryWrapper<Permission>().like(StrUtil.isBlank(name),"pername",name));

        return Result.succ(pageData);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:perm:save')")
    public Result save(@Validated @RequestBody Permission permission){
        permission.setPerstatu(Const.STATUS_ON);
        permissionService.save(permission);
        return Result.succ(permission);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:perm:update')")
    public Result update(@Validated @RequestBody Permission permission){
        permissionService.updateById(permission);

        //更新缓存
        adminsService.clearAdminAuthorityInfoByPermisId(permission.getPerid());

        return Result.succ(permission);
    }

    @PostMapping("/delete")
    @Transactional
    @PreAuthorize("hasAuthority('sys:perm:delete')")
    public Result info(@RequestBody Integer[] perids){
        permissionService.removeByIds(Arrays.asList(perids));
        //删除中间表
        adminsPermisService.remove(new QueryWrapper<AdminsPermis>().in("perid",perids));
        permPercService.remove(new QueryWrapper<PermPerc>().in("perid",perids));

        //清理缓存
        Arrays.stream(perids).forEach(perid -> {
            adminsService.clearAdminAuthorityInfoByPermisId(perid);
        });

        return Result.succ("");
    }

    /*分配权限*/
    @Transactional
    @PostMapping("/pcitems/{perid}")
    @PreAuthorize("hasAuthority('sys:perm:pcitems')")
    public Result info(@PathVariable("perid") Integer perid, @RequestBody Integer[] pcids){

        List<PermPerc> permPercs = new ArrayList<>();

        Arrays.stream(pcids).forEach(pcid -> {
            PermPerc permPerc = new PermPerc();
            permPerc.setPcid(pcid);
            permPerc.setPerid(perid);

            permPercs.add(permPerc);
        });

        //先删除原来的记录，再保存新的
        permPercService.remove(new QueryWrapper<PermPerc>().eq("perid",perid));
        permPercService.saveBatch(permPercs);

        //删除缓存
        adminsService.clearAdminAuthorityInfoByPermisId(perid);

        return Result.succ(pcids);
    }

}
